package com.jfinal.demo.controller;

import com.jfinal.core.Controller;
import com.jfinal.demo.model.User;
import com.jfinal.kit.PathKit;
import com.jfinal.log.Logger;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;

import java.io.File;
import java.io.UnsupportedEncodingException;

/**
 * Title:
 * Description: form crud
 *
 * @version 2.0
 * @author: Yung Fu(FUYUNGCN AT GMAIL DOT com)
 * @since: 14-9-21 下午2:01
 */
public class FormController extends Controller {

    Logger logger = Logger.getLogger(this.getClass());

    /**
     * /form/saveUser
     */
    public void saveUser() {
        for (int i = 0; i < 10; i++) {
            new User().set("name", "fy" + i).set("address", "湖南长沙").set("idCard", "4301129892237897").save();
        }

        renderText("保存成功！");
    }

    /**
     * /form/getUserById/1
     */
    public void getUserById() {
        int id = Integer.parseInt(getPara(0));

        User user = User.dao.findById(id);
        if (user != null)
            renderText("name: " + user.get("name"));
        else
            renderText("没有查询到Id为" + id + "的记录！");
    }

    /**
     * /form/deleteUserById/1
     */
    public void deleteUserById() {
        int id = Integer.parseInt(getPara(0));

        User user = User.dao.findById(id);
        if (user != null) {
            boolean flag = User.dao.deleteById(id);
            if (flag)
                renderText("删除id为" + id + "的记录！");
        } else
            renderText("删除失败！");

    }

    /**
     * /form/updateUseNamerById/1-name
     *
     * @throws UnsupportedEncodingException
     */
    public void updateUseNamerById() throws UnsupportedEncodingException {
        int id = Integer.parseInt(getPara(0));
        String name = getPara(1);

        User user = User.dao.findById(id);
        if (user != null) {
            boolean flag = user.set("name", name).update();
            if (flag)
                renderText("更新id为：" + id + "记录的name字段为：" + User.dao.findById(id).get("name"));
        } else
            renderText("更新失败！");
    }

    /**
     * /form/getUserBy/1
     */
    public void getUserBy() {
        int id = Integer.parseInt(getPara(0));
        // 取其中几个字段sql方式
//        List<User> userList = User.dao.find("select name, address from `user` where id = "+ id);
//        for (User user : userList) {
//            logger.info("name: " + user.get("name") + " address: " + user.get("address") + " idCard: " + user.get("idCard"));
//            renderText("name: " + user.get("name") + " address: " + user.get("address") + " idCard: " + user.get("idCard"));
//        }

        // findById方式
        User user = User.dao.findById(id, "name, address");
        renderText("name: " + user.get("name") + " address: " + user.get("address") + " idCard: " + user.get("idCard"));
    }

    /**
     * /form/userPaginate/18-1-10
     * 表示从id大于18的记录，按照每页10条进行分页，返回第一页数据
     */
    public void userPaginate() {
        int id = Integer.parseInt(getPara(0));
        int pageNumber = Integer.parseInt(getPara(1));// 当前页数
        int pageSize = Integer.parseInt(getPara(2));// 每页显示条数

        Page<User> userPage = User.dao.paginate(pageNumber, pageSize, "select *", "from user where id > ?", id);

        StringBuilder sb = new StringBuilder();
        sb.append("PageNumber: ").append(userPage.getPageNumber())
                .append("PageSize: ").append(userPage.getPageSize())
                .append("TotalPage: ").append(userPage.getTotalPage())
                .append("TotalRow").append(userPage.getTotalRow())
                .append("\n");

        for (User user : userPage.getList()) {
            logger.info("id: "+ user.getInt("id") + "name: " + user.get("name") + " address: " + user.get("address") + " idCard: " + user.get("idCard"));
            sb.append("id: ").append(user.getInt("id")).append("name: ").append(user.get("name")).append(" address: ").append(user.get("address")).append(" idCard: ").append(user.get("idCard")).append("\n");
        }
        renderText(sb.toString());
    }

    public void uploadFile() {
        String uploadDir = File.separator + "upload" + File.separator + "contract" + File.separator;
        String path_tmp = PathKit.getWebRootPath() + uploadDir;
        UploadFile uploadFile = getFile("upload", path_tmp);// 真正保存
        String fileName = uploadFile.getFileName();
        String real_path = uploadFile.getSaveDirectory();

        render("操作成功！fileName:" + fileName + " real_path:" + real_path);
    }
}
